﻿@model Model.NumberingRule
@{
    Layout = null;
}

<!-- 新增面板头部 -->
<div class="modal-header">
    <h5 class="modal-title">新增编号规则</h5>
    <button type="button" class="close-modal-btn close">&times;</button>
</div>

<!-- 新增面板内容 -->
<div class="modal-body">
    <form id="formAdd" action="@Url.Action("Create", "NumberingRules")" method="post">
        @Html.AntiForgeryToken()

        <!-- 隐藏字段 -->
        <input type="hidden" name="CreateBy" value="admin" />
        <input type="hidden" name="UpdateBy" value="admin" />
        <input type="hidden" name="IsDelete" value="0" />
        <input type="hidden" name="NumberGenerationRule" id="NumberGenerationRule" value="" />
        <input type="hidden" name="SelectedTimeRule" id="SelectedTimeRule" value="年月日" />

        <!-- 目标表单 -->
        <div class="form-group mb-3">
            <label class="form-label">目标表单 <span class="text-danger">*</span></label>
            <input type="text"
                   id="TargetForm"
                   name="TargetForm"
                   value="@Model?.TargetForm"
                   class="form-control"
                   placeholder="例如：货品信息、入库单"
                   required
                   maxlength="50" />
        </div>

        <!-- 编号前缀 -->
        <div class="form-group mb-3">
            <label class="form-label">编号前缀 <span class="text-danger">*</span></label>
            <input type="text"
                   id="NumberPrefix"
                   name="NumberPrefix"
                   value="@Model?.NumberPrefix"
                   class="form-control"
                   placeholder="例如：HP、RK"
                   required />
        </div>

        <!-- 时间规则 - 修改为单选按钮组 -->
        <div class="form-group mb-3">
            <label class="form-label">时间规则 <span class="text-danger">*</span></label>
            <div class="time-rule-radio d-flex flex-wrap gap-3">
                <!-- 年YY -->
                <label class="radio-label d-flex align-items-center">
                    <input type="checkbox" name="TimeRuleRadio" value="年" class="time-rule-radio-btn" /> 年YY
                </label>

                <!-- 年月YYMM -->
                <label class="radio-label d-flex align-items-center">
                    <input type="checkbox" name="TimeRuleRadio" value="年月" class="time-rule-radio-btn" /> 年月YYMM
                </label>

                <!-- 年月日YYMMDD -->
                <label class="radio-label d-flex align-items-center">
                    <input type="checkbox" name="TimeRule" id="TimeRule" value="年月日" class="time-rule-radio-btn" checked /> 年月日YYMMDD
                </label>
            </div>
            <small class="form-text text-muted">请选择一项时间规则</small>
        </div>

        <!-- 流水号位数、步长 -->
        <div class="row g-3 mb-3">
            <div class="col-md-6">
                <label class="form-label">流水号位数 <span class="text-danger">*</span></label>
                <input type="text"
                       id="SerialNumberDigit"
                       name="SerialNumberDigit"
                       value="@Model?.SerialNumberDigit"
                       class="form-control"
                       placeholder="例如：3、5"
                       required />
            </div>
            <div class="col-md-6">
                <label class="form-label">步长 <span class="text-danger">*</span></label>
                <input type="number"
                       id="Step"
                       name="Step"
                       value="@(Model?.Step ?? 1)"
                       class="form-control"
                       min="1"
                       required />
            </div>
        </div>

        <!-- 编号预览显示 -->
        <div class="form-group mb-3">
            <label class="form-label">编号预览</label>
            <div id="previewDisplay" class="form-control" style="background-color: #f8f9fa; color: #6c757d;">
                请输入完整信息后生成预览
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary close-modal-btn">取消</button>
            <button type="button" class="btn btn-success" id="btnSubmit">保存</button>
        </div>
    </form>
</div>

<style>
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        border-bottom: 1px solid #eee;
    }

    .modal-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
    }

    .close {
        background: transparent;
        border: none;
        font-size: 20px;
        cursor: pointer;
        color: #666;
    }

    .modal-body {
        padding: 15px;
        max-height: calc(100vh - 150px);
        overflow-y: auto;
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-label {
        display: block;
        margin-bottom: 5px;
        font-weight: 600;
        font-size: 13px;
        color: #333;
    }

    .form-control {
        width: 100%;
        height: 36px;
        padding: 6px 12px;
        font-size: 14px;
        border: 1px solid #ddd;
        border-radius: 4px;
        transition: border-color 0.2s;
    }

        .form-control:focus {
            border-color: #28a745;
            outline: none;
            box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.1);
        }

    .time-rule-radio {
        margin-top: 8px;
    }

    .radio-label {
        font-size: 14px;
        color: #333;
        cursor: pointer;
    }

        .radio-label input {
            width: 16px;
            height: 16px;
            accent-color: #28a745;
            margin-right: 5px;
        }

    .row.g-3 {
        display: flex;
        gap: 15px;
        margin: 0 -7.5px;
    }

    .col-md-6 {
        flex: 1;
        padding: 0 7.5px;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        padding: 10px 15px;
        border-top: 1px solid #eee;
    }

    .btn-outline-secondary {
        height: 36px;
        padding: 6px 16px;
        border: 1px solid #ced4da;
        color: #495057;
        background-color: transparent;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
    }

        .btn-outline-secondary:hover {
            background-color: #f5f5f5;
        }

    .btn-success {
        height: 36px;
        padding: 6px 16px;
        background-color: #28a745;
        border-color: #28a745;
        color: #fff;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
    }

        .btn-success:hover {
            background-color: #218838;
        }

    .text-danger {
        color: #dc3545;
    }

    .form-text {
        font-size: 12px;
        margin-top: 5px;
    }
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        // 关闭按钮事件
        $(".close-modal-btn, .close").click(function () {
            $("#editPanel").hide();
        });

        // 时间规则单选按钮事件
        $(".time-rule-radio-btn").change(function () {
            if ($(this).prop('checked')) {
                $("#TimeRule").val($(this).val());
                generatePreview();
            }
        });

        // 实时生成预览
        function generatePreview() {
            const targetForm = $.trim($("#TargetForm").val());
            const numberPrefix = $.trim($("#NumberPrefix").val());
            const serialDigit = $("#SerialNumberDigit").val();
            const step = parseInt($("#Step").val() || 1);
            const timeRule = $("#TimeRule").val();

            if (targetForm && numberPrefix && serialDigit && timeRule) {
                // 生成编号规则字符串（包含时间规则）
                let ruleString = numberPrefix;

                // 根据时间规则添加时间格式
                switch (timeRule) {
                    case "年":
                        ruleString += "YY";
                        break;
                    case "年月":
                        ruleString += "YYMM";
                        break;
                    case "年月日":
                        ruleString += "YYMMDD";
                        break;
                }

                // 验证流水号位数是否为数字
                if (!isNaN(serialDigit) && parseInt(serialDigit) > 0) {
                    ruleString += "0".repeat(parseInt(serialDigit));
                } else {
                    ruleString += "000"; // 默认值
                }

                // 生成预览编号
                let previewNumber = numberPrefix;

                // 添加时间部分
                const now = new Date();
                const year = now.getFullYear().toString().slice(-2); // 两位年份
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');

                switch (timeRule) {
                    case "年":
                        previewNumber += year;
                        break;
                    case "年月":
                        previewNumber += year + month;
                        break;
                    case "年月日":
                        previewNumber += year + month + day;
                        break;
                }

                // 添加流水号部分
                if (!isNaN(serialDigit) && parseInt(serialDigit) > 0) {
                    previewNumber += "1".padStart(parseInt(serialDigit), '0');
                } else {
                    previewNumber += "001"; // 默认值
                }

                // 更新显示和隐藏字段
                $("#previewDisplay").text(previewNumber).css("color", "#28a745");
                $("#NumberGenerationRule").val(ruleString);
            } else {
                $("#previewDisplay").text("请输入完整信息后生成预览").css("color", "#6c757d");
                $("#NumberGenerationRule").val("");
            }
        }

        // 绑定输入事件
        $("#TargetForm, #NumberPrefix, #SerialNumberDigit, #Step").on("input", generatePreview);
        $(".time-rule-radio-btn").on("change", generatePreview);

        // 保存按钮点击事件
        $("#btnSubmit").click(function () {
            // 1. 验证目标表单
            const targetForm = $.trim($("#TargetForm").val());
            if (!targetForm) {
                alert("请输入目标表单");
                return;
            }
            if (targetForm.length > 50) {
                alert("目标表单名称不能超过50个字符");
                return;
            }

            // 2. 验证编号前缀
            const numberPrefix = $("#NumberPrefix").val().trim();
            if (!numberPrefix) {
                alert("请输入编号前缀");
                return;
            }

            // 3. 验证时间规则
            const timeRule = $("#SelectedTimeRule").val();
            if (!timeRule) {
                alert("请选择时间规则");
                return;
            }

            // 4. 验证流水号位数
            const serialDigit = $("#SerialNumberDigit").val().trim();
            if (!serialDigit) {
                alert("请输入流水号位数");
                return;
            }
            if (isNaN(serialDigit) || parseInt(serialDigit) < 1) {
                alert("流水号位数必须是大于0的数字");
                return;
            }

            // 5. 验证步长
            const step = parseInt($("#Step").val() || 0);
            if (isNaN(step) || step < 1) {
                alert("请输入有效的步长（至少1）");
                return;
            }

            // 6. 确保隐藏字段有值
            generatePreview(); // 最后生成一次确保数据正确

            // 7. 显示加载状态
            $("#btnSubmit").prop("disabled", true).text("保存中...");

            // 8. AJAX提交表单
            $.ajax({
                url: "@Url.Action("Create", "NumberingRules")",
                type: "POST",
                data: $("#formAdd").serialize(),
                success: function (response) {
                    $("#btnSubmit").prop("disabled", false).text("保存");

                    if (response.success) {
                        alert("新增成功！");
                        $("#editPanel").hide();
                        // 刷新页面显示新数据
                        if (window.refreshRuleTable) {
                            window.refreshRuleTable();
                        } else {
                            location.reload();
                        }
                    } else {
                        alert("新增失败：" + (response.message || "未知错误"));
                    }
                },
                error: function (xhr, status, error) {
                    $("#btnSubmit").prop("disabled", false).text("保存");
                    console.error("AJAX请求失败:", {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                    alert(`网络错误，新增失败（状态码：${xhr.status}）\n详细错误请查看控制台`);
                }
            });
        });

        // 初始化预览
        generatePreview();
    });
</script>